package com.cqu.ssologin.controller;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

import com.cqu.ssologin.pojo.User;
import com.cqu.ssologin.utils.LoginCacheUtil;


@Controller
@RequestMapping("/login")
public class LoginController {
    
    //虚拟database
    private static Set<User> dbUser;
    static {
        dbUser = new HashSet<>();
        dbUser.add(new User(1, "zhangsan", "1234561"));
        dbUser.add(new User(2, "lisi", "1234562"));
        dbUser.add(new User(3, "wangwu", "1234563"));
    }


    @PostMapping
    public String doLogin(User user, HttpSession session, HttpServletResponse response){
        String target = (String)session.getAttribute("target");
        //模拟从数据库中通过用户名和密码查找用户
        Optional<User> first = dbUser.stream().filter(dbUser -> dbUser.getUsername().equals(user.getUsername()) &&
                dbUser.getPassword().equals(user.getPassword()))
                .findFirst();
        //判断用户是否登录成功
        if (first.isPresent()) {
            //保存用户登录信息
            String token = UUID.randomUUID().toString();
            Cookie cookie = new Cookie("TOKEN", token);
            cookie.setPath("/");
            cookie.setDomain("localhost");
            response.addCookie(cookie);
            LoginCacheUtil.loginUser.put(token, first.get());
        } else {
            //登录失败
            session.setAttribute("msg", "用户名或密码错误!");
            return "login";
        }
        //重定向到target地址
        return "redirect:" + target;
    }


    @GetMapping("info")
    @ResponseBody
    public ResponseEntity<User> getUserInfo(String token){
        if(!StringUtils.isEmpty(token)){
            User user = LoginCacheUtil.loginUser.get(token);
            return ResponseEntity.ok(user);
        } else{
            return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
        }
    }

}
